/**
 * Copyright(c) Yystar Technology Co.,Ltd
 * project：security
 * package：com.yystar.security.domain.dao
 * fileName：OpUserDetailsDao.java
 * date：2013-6-26
 */
package com.yystar.security.op.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl;

/**
 * @author Vistaa Peng
 * @date 2013-6-26
 * @todo TODO
 * @modify <BR>
 *         1.2013-6-26 Vistaa Peng Create file.
 */
public class OpUserDetailsDao extends JdbcDaoImpl {
	private static Logger log = Logger.getLogger(OpUserDetailsDao.class);
	public static final String USERS_BY_USERNAME_QUERY = "SELECT OpCode, Password, Status FROM test.Op where OpCode = ?";
	public static final String AUTHORITIES_BY_USERNAME_QUERY = "SELECT Level FROM test.Op where OpCode = ?";
	public static final String GROUP_AUTHORITIES_BY_USERNAME_QUERY = "select g.id, g.group_name, ga.authority "
			+ "from groups g, group_members gm, group_authorities ga " + "where gm.username = ? "
			+ "and g.id = ga.group_id " + "and g.id = gm.group_id";

	@Override
	protected List<UserDetails> loadUsersByUsername(String username) {
		super.setUsersByUsernameQuery(USERS_BY_USERNAME_QUERY);
		return super.loadUsersByUsername(username);
	}

	@Override
	protected List<GrantedAuthority> loadUserAuthorities(String username) {
		String levelsString = getJdbcTemplate().queryForObject(AUTHORITIES_BY_USERNAME_QUERY,
				new Object[] { username }, String.class);
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		if (levelsString != null) {
			for (String role : levelsString.split(",")) {
				authorities.add(new SimpleGrantedAuthority(role));
			}
		}
		// TODO optimized in the future
		log.info("Action: " + username + "logining at time: " + new Date().toString());
		return authorities;

	}

}
